package com.carp.sentinel.config;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;


@Component
public class ZookeeperSentinelConfig {
    @Value("${spring.application.name}")
    private String appName;

    public static final String RULE_ROOT_PATH = "/sentinel_rule_config";
    public static final String FLOW_RULE_PATH = "/flow_rule";
    public static final String DEGRADE_RULE_PATH = "/degrade_rule";

    @PostConstruct
    public void loadRules() {
        final String remoteAddress = "127.0.0.1:2181";
        final String flowPath = RULE_ROOT_PATH + FLOW_RULE_PATH + "/" + appName;

        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(remoteAddress, flowPath,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());


        final String degradePath = RULE_ROOT_PATH + DEGRADE_RULE_PATH + "/" + appName;
        ReadableDataSource<String, List<DegradeRule>> degradeRuleDataSource = new ZookeeperDataSource<>(remoteAddress, degradePath,
                source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
                }));
        DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty());

    }
}